'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { 
  UserCheck, 
  UserX, 
  Calendar, 
  Plus,
  Search,
  Check,
  X,
  AlertCircle
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { FadeIn } from '@/components/ui/motion';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/components/ui/use-toast';
import { Toaster } from 'sonner';
import { 
  attendanceService, 
  AttendanceStatus, 
  StudentAttendanceDetail, 
  AttendanceStatistics,
  BatchAttendanceSubmitRequest
} from '@/services/attendanceService';

export default function AttendancePage() {
  const [activeTab, setActiveTab] = useState('today');
  const [searchTerm, setSearchTerm] = useState('');
  const [attendanceDate, setAttendanceDate] = useState(new Date().toISOString().split('T')[0]);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const { toast } = useToast();
  
  // 状态数据
  const [todayStats, setTodayStats] = useState<AttendanceStatistics | null>(null);
  const [weeklyStats, setWeeklyStats] = useState<AttendanceStatistics[]>([]);
  const [studentAttendance, setStudentAttendance] = useState<StudentAttendanceDetail[]>([]);
  const [modifiedRecords, setModifiedRecords] = useState<Map<number, { status: AttendanceStatus, remarks: string }>>(new Map());
  
  // 添加引用来跟踪是否已经加载数据
  const todayStatsLoaded = useRef(false);
  const weeklyStatsLoaded = useRef(false);
  
  // 错误处理函数
  const handleError = useCallback((message: string, error: any) => {
    console.error(message, error);
    toast({
      title: message,
      description: "请稍后重试",
      variant: "destructive"
    });
  }, [toast]);
  
  // 获取今日考勤统计
  useEffect(() => {
    // 如果已经加载过数据，则不再重复加载
    if (todayStatsLoaded.current) return;
    
    let isMounted = true;
    
    const fetchTodayStats = async () => {
      try {
        const data = await attendanceService.getTodayStats();
        if (isMounted && data) {
          setTodayStats(data);
          todayStatsLoaded.current = true;
        }
      } catch (error) {
        if (isMounted) {
          handleError('获取今日考勤统计失败', error);
        }
      }
    };
    
    fetchTodayStats();
    
    return () => {
      isMounted = false;
    };
  }, [handleError]);
  
  // 获取近七天考勤统计
  useEffect(() => {
    if (activeTab !== 'history' || weeklyStatsLoaded.current) return;
    
    let isMounted = true;
    
    const fetchWeeklyStats = async () => {
      try {
        const data = await attendanceService.getLastSevenDaysStats();
        if (isMounted && Array.isArray(data)) {
          setWeeklyStats(data);
          weeklyStatsLoaded.current = true;
        }
      } catch (error) {
        if (isMounted) {
          handleError('获取近七天考勤统计失败', error);
        }
      }
    };
    
    fetchWeeklyStats();
    
    return () => {
      isMounted = false;
    };
  }, [activeTab, handleError]);
  
  // 重置加载状态，用于手动刷新数据
  const refreshData = useCallback(() => {
    // 清除服务层缓存
    attendanceService.clearCache();
    
    // 重置加载状态
    todayStatsLoaded.current = false;
    weeklyStatsLoaded.current = false;
    
    // 重新触发数据加载
    const fetchData = async () => {
      try {
        const data = await attendanceService.getTodayStats();
        setTodayStats(data);
        todayStatsLoaded.current = true;
        
        if (activeTab === 'history') {
          const weeklyData = await attendanceService.getLastSevenDaysStats();
          setWeeklyStats(weeklyData);
          weeklyStatsLoaded.current = true;
        }
      } catch (error) {
        handleError('刷新数据失败', error);
      }
    };
    
    fetchData();
  }, [activeTab, handleError]);
  
  // 获取指定日期的学生考勤详情
  const fetchStudentAttendance = async (date: string) => {
    setIsLoading(true);
    try {
      const data = await attendanceService.getAttendanceDetailsByDate(date);
      setStudentAttendance(data || []);
      // 重置修改记录
      setModifiedRecords(new Map());
    } catch (error) {
      // 确保在错误情况下也设置为空数组
      setStudentAttendance([]);
      handleError('获取学生考勤详情失败', error);
    } finally {
      setIsLoading(false);
    }
  };
  
  // 处理日期选择变更
  const handleDateChange = (date: string) => {
    setAttendanceDate(date);
    fetchStudentAttendance(date);
  };
  
  // 处理考勤状态变更
  const handleAttendanceChange = (studentId: number, status: AttendanceStatus, remarks: string = '') => {
    // 更新修改记录
    setModifiedRecords(prev => {
      const newMap = new Map(prev);
      newMap.set(studentId, { status, remarks });
      return newMap;
    });
    
    // 更新UI显示
    setStudentAttendance(prev => prev.map(student => {
      if (student.studentId === studentId) {
        return {
          ...student,
          status: status,
          remarks: remarks
        };
      }
      return student;
    }));
  };
  
  // 保存考勤记录
  const handleSaveAttendance = async () => {
    if (modifiedRecords.size === 0) {
      toast({
        title: "没有修改记录",
        description: "请先修改学生考勤状态",
        variant: "default"
      });
      return;
    }
    
    setIsSaving(true);
    
    try {
      const records = Array.from(modifiedRecords.entries()).map(([studentId, data]) => ({
        studentId,
        status: data.status,
        remarks: data.remarks
      }));
      
      const request: BatchAttendanceSubmitRequest = {
        date: attendanceDate,
        attendances: records
      };
      
      // 打印提交的参数
      console.log('提交考勤参数:', JSON.stringify(request, null, 2));
      
      const result = await attendanceService.batchSubmitAttendance(request);
      
      // 打印响应结果
      console.log('提交考勤响应:', result);
      
      toast({
        title: "考勤记录保存成功",
        description: `成功提交 ${result} 条考勤记录`,
        variant: "default"
      });
      
      // 重新获取数据
      fetchStudentAttendance(attendanceDate);
      
      // 如果是今天的考勤，刷新今日统计
      if (attendanceDate === new Date().toISOString().split('T')[0]) {
        todayStatsLoaded.current = false; // 重置加载状态
        const todayData = await attendanceService.getTodayStats();
        setTodayStats(todayData);
        todayStatsLoaded.current = true;
      }
      
      // 关闭对话框
      setDialogOpen(false);
    } catch (error) {
      handleError('保存考勤记录失败', error);
    } finally {
      setIsSaving(false);
    }
  };
  
  // 过滤学生列表
  const filteredStudents = studentAttendance ? studentAttendance.filter(student => 
    student.name.toLowerCase().includes(searchTerm.toLowerCase())
  ) : [];
  
  // 获取考勤状态显示
  const getStatusBadge = (status: AttendanceStatus | null) => {
    if (status === 'PRESENT') {
      return <Badge className="bg-green-100 text-green-800 hover:bg-green-200">出勤</Badge>;
    } else if (status === 'ABSENT') {
      return <Badge className="bg-red-100 text-red-800 hover:bg-red-200">缺勤</Badge>;
    } else if (status === 'LEAVE') {
      return <Badge className="bg-yellow-100 text-yellow-800 hover:bg-yellow-200">请假</Badge>;
    } else {
      return <Badge className="bg-gray-100 text-gray-800 hover:bg-gray-200">未录入</Badge>;
    }
  };

  return (
    <FadeIn>
      <Toaster />
      <div className="container mx-auto py-6">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">考勤记录</h1>
          <div className="flex space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
              <Input
                type="search"
                placeholder="搜索学生..."
                className="pl-8 w-[200px] md:w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
              <DialogTrigger asChild>
                <Button className="flex items-center">
                  <Plus className="mr-2 h-4 w-4" />
                  录入考勤
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-4xl">
                <DialogHeader>
                  <DialogTitle>录入考勤信息</DialogTitle>
                  <DialogDescription>
                    选择日期并录入学生考勤状态
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid gap-2">
                    <Label htmlFor="attendance-date">考勤日期</Label>
                    <Input
                      id="attendance-date"
                      type="date"
                      value={attendanceDate}
                      onChange={(e) => handleDateChange(e.target.value)}
                    />
                  </div>
                  
                  {isLoading ? (
                    <div className="flex justify-center items-center py-8">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                    </div>
                  ) : (
                    <div className="overflow-x-auto max-h-[400px]">
                      <table className="w-full text-sm text-left">
                        <thead className="text-xs text-gray-700 uppercase bg-gray-50 sticky top-0">
                          <tr>
                            <th className="px-4 py-3">学号</th>
                            <th className="px-4 py-3">姓名</th>
                            <th className="px-4 py-3">性别</th>
                            <th className="px-4 py-3">考勤状态</th>
                            <th className="px-4 py-3">备注</th>
                            <th className="px-4 py-3">操作</th>
                          </tr>
                        </thead>
                        <tbody>
                          {filteredStudents.map((student) => (
                            <tr key={student.studentId} className="bg-white border-b">
                              <td className="px-4 py-3">{student.studentNumber}</td>
                              <td className="px-4 py-3 font-medium">{student.name}</td>
                              <td className="px-4 py-3">{student.gender}</td>
                              <td className="px-4 py-3">
                                {getStatusBadge(student.status)}
                              </td>
                              <td className="px-4 py-3 max-w-[200px] truncate">
                                {student.remarks || '-'}
                              </td>
                              <td className="px-4 py-3">
                                <div className="flex space-x-1">
                                  <Button 
                                    size="sm" 
                                    variant={student.status === 'PRESENT' ? "default" : "outline"} 
                                    className={`h-8 ${student.status === 'PRESENT' ? 'bg-green-600 hover:bg-green-700' : ''}`}
                                    onClick={() => handleAttendanceChange(student.studentId, 'PRESENT', '准时到校')}
                                  >
                                    <UserCheck className="h-4 w-4 mr-1" />
                                    <span>出勤</span>
                                  </Button>
                                  <Button 
                                    size="sm" 
                                    variant={student.status === 'ABSENT' ? "default" : "outline"} 
                                    className={`h-8 ${student.status === 'ABSENT' ? 'bg-red-600 hover:bg-red-700' : ''}`}
                                    onClick={() => handleAttendanceChange(student.studentId, 'ABSENT', '未到校')}
                                  >
                                    <UserX className="h-4 w-4 mr-1" />
                                    <span>缺勤</span>
                                  </Button>
                                  <Button 
                                    size="sm" 
                                    variant={student.status === 'LEAVE' ? "default" : "outline"} 
                                    className={`h-8 ${student.status === 'LEAVE' ? 'bg-yellow-600 hover:bg-yellow-700' : ''}`}
                                    onClick={() => handleAttendanceChange(student.studentId, 'LEAVE', '请假')}
                                  >
                                    <Calendar className="h-4 w-4 mr-1" />
                                    <span>请假</span>
                                  </Button>
                                </div>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
                  <Button 
                    onClick={handleSaveAttendance} 
                    disabled={isSaving || modifiedRecords.size === 0}
                  >
                    {isSaving ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                        保存中...
                      </>
                    ) : '保存考勤'}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>
        
        {/* 考勤统计卡片 */}
        <div className="mb-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <UserCheck className="h-5 w-5 mr-2" />
                今日考勤概览
                <Button 
                  variant="ghost" 
                  size="sm" 
                  className="ml-2" 
                  onClick={refreshData}
                  title="刷新数据"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="lucide lucide-refresh-cw">
                    <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"></path>
                    <path d="M21 3v5h-5"></path>
                    <path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"></path>
                    <path d="M3 21v-5h5"></path>
                  </svg>
                </Button>
              </CardTitle>
              <CardDescription>
                {new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })}
              </CardDescription>
            </CardHeader>
            <CardContent>
              {!todayStats ? (
                <div className="flex justify-center items-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="bg-green-50 p-4 rounded-lg">
                    <div className="flex justify-between items-center">
                      <div>
                        <p className="text-sm text-gray-500">出勤</p>
                        <p className="text-2xl font-bold text-green-600">{todayStats.presentCount}人</p>
                        <p className="text-sm text-gray-500">{todayStats.presentRate.toFixed(1)}%</p>
                      </div>
                      <div className="p-2 bg-green-100 rounded-full">
                        <UserCheck className="h-6 w-6 text-green-600" />
                      </div>
                    </div>
                  </div>
                  
                  <div className="bg-red-50 p-4 rounded-lg">
                    <div className="flex justify-between items-center">
                      <div>
                        <p className="text-sm text-gray-500">缺勤</p>
                        <p className="text-2xl font-bold text-red-600">{todayStats.absentCount}人</p>
                        <p className="text-sm text-gray-500">{todayStats.absentRate.toFixed(1)}%</p>
                      </div>
                      <div className="p-2 bg-red-100 rounded-full">
                        <UserX className="h-6 w-6 text-red-600" />
                      </div>
                    </div>
                  </div>
                  
                  <div className="bg-yellow-50 p-4 rounded-lg">
                    <div className="flex justify-between items-center">
                      <div>
                        <p className="text-sm text-gray-500">请假</p>
                        <p className="text-2xl font-bold text-yellow-600">{todayStats.leaveCount}人</p>
                        <p className="text-sm text-gray-500">{todayStats.leaveRate.toFixed(1)}%</p>
                      </div>
                      <div className="p-2 bg-yellow-100 rounded-full">
                        <Calendar className="h-6 w-6 text-yellow-600" />
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
        
        {/* 选项卡 */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="mb-6">
          <TabsList className="mb-4">
            <TabsTrigger value="today">今日考勤</TabsTrigger>
            <TabsTrigger value="history">历史记录</TabsTrigger>
          </TabsList>
          
          {/* 今日考勤选项卡 */}
          <TabsContent value="today">
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">学生考勤状态</CardTitle>
                <CardDescription>点击录入考勤按钮录入今日考勤</CardDescription>
              </CardHeader>
              <CardContent className="flex flex-col items-center justify-center py-12">
                <AlertCircle className="h-16 w-16 text-gray-300 mb-4" />
                <p className="text-gray-500 text-center">请点击右上角"录入考勤"按钮开始录入学生考勤信息</p>
                <Button 
                  className="mt-6" 
                  onClick={() => {
                    setAttendanceDate(new Date().toISOString().split('T')[0]);
                    fetchStudentAttendance(new Date().toISOString().split('T')[0]);
                    setDialogOpen(true);
                  }}
                >
                  <Plus className="mr-2 h-4 w-4" />
                  录入今日考勤
                </Button>
              </CardContent>
            </Card>
          </TabsContent>
          
          {/* 历史记录选项卡 */}
          <TabsContent value="history">
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">考勤历史记录</CardTitle>
                <CardDescription>近七天考勤情况统计</CardDescription>
              </CardHeader>
              <CardContent>
                {weeklyStats.length === 0 ? (
                  <div className="flex justify-center items-center py-8">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                  </div>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm text-left">
                      <thead className="text-xs text-gray-700 uppercase bg-gray-50">
                        <tr>
                          <th className="px-6 py-3">日期</th>
                          <th className="px-6 py-3">出勤人数</th>
                          <th className="px-6 py-3">缺勤人数</th>
                          <th className="px-6 py-3">请假人数</th>
                          <th className="px-6 py-3">总人数</th>
                          <th className="px-6 py-3">出勤率</th>
                        </tr>
                      </thead>
                      <tbody>
                        {weeklyStats.map((day, index) => (
                          <tr key={index} className="bg-white border-b">
                            <td className="px-6 py-4">{day.date}</td>
                            <td className="px-6 py-4 text-green-600">{day.presentCount}</td>
                            <td className="px-6 py-4 text-red-600">{day.absentCount}</td>
                            <td className="px-6 py-4 text-yellow-600">{day.leaveCount}</td>
                            <td className="px-6 py-4">{day.totalCount}</td>
                            <td className="px-6 py-4">
                              {day.presentRate.toFixed(1)}%
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </FadeIn>
  );
}
